package projectsupporter.common.formbase;

import java.io.File;
import java.io.FilenameFilter;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionAdapter;


public class FolderSelectDialog {
	private Shell folderselectshell = null; // 文件件选择对话框
	private Composite foldertreecomposite = null;// 文件夹目录显示组件
	private Composite buttoncomposite = null;
	private Label foldernamelabel = null;
	private Text foldernametext = null;
	private Button okbutton = null;
	private Button cancelbutton = null;
	private Tree folderdirectree = null;// 文件夹目录树
	private File folderabsolutepath = null;// 单击确定按钮时，所选中的文件夹绝对路径

	/**
	 * This method initializes mesgTipShell
	 */
	private void createSShell() {
		// SWT.TOOL是没有标题行,没有最大化、最小化和关闭按钮的窗口
		folderselectshell = new Shell();
		folderselectshell.setText("选择文件夹");
		folderselectshell.setSize(new Point(462, 489));
		folderselectshell.setLayout(null);
		createFoldertreecomposite();
		createButtoncomposite();
		// //设置窗口在屏幕上的初始位置，在屏幕的右下角显示窗口
		// WindowPosition shellposition=new WindowPosition();
		// shellposition.rightBelowCenter(folderselectshell);

	}

	/**
	 * 打开文件夹选择对话框
	 */
	public void openFolderSelectDialog() {
		final Display display = Display.getDefault();
		createSShell();// 初始化文件夹选择对话框
		creatTreeControl(foldertreecomposite);// 以属性结构显示系统文件夹
		folderselectshell.open();// 打开文件夹选择窗口
		while (!folderselectshell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
	}

	/**
	 * 关闭文件夹选择对话框
	 */
	protected void closeFolderSelectDialog() {
		if (folderselectshell != null)
			folderselectshell.dispose();// 释放底层的资源
	}

	/**
	 * This method initializes foldertreecomposite
	 * 
	 */
	private void createFoldertreecomposite() {
		foldertreecomposite = new Composite(folderselectshell, SWT.NONE);
		// foldertreecomposite.setBackground(Col);
		// foldertreecomposite.setLayout(new GridLayout());
		foldertreecomposite.setBounds(new Rectangle(16, 16, 428, 359));
	}

	/**
	 * This method initializes buttoncomposite
	 * 
	 */
	private void createButtoncomposite() {
		buttoncomposite = new Composite(folderselectshell, SWT.NONE);
		buttoncomposite.setLayout(null);
		buttoncomposite.setBounds(new Rectangle(16, 381, 428, 64));
		foldernamelabel = new Label(buttoncomposite, SWT.NONE);
		foldernamelabel.setText("文件夹名：");
		foldernamelabel.setSize(new Point(65, 15));
		foldernamelabel.setFont(new Font(Display.getDefault(), "/u5b8b/u4f53",
				10, SWT.NORMAL));
		foldernamelabel.setLocation(new Point(5, 14));
		foldernametext = new Text(buttoncomposite, SWT.BORDER | SWT.READ_ONLY);
		foldernametext.setEditable(false);
		foldernametext.setSize(new Point(348, 18));
		foldernametext.setFont(new Font(Display.getDefault(), "/u5b8b/u4f53",
				10, SWT.NORMAL));
		foldernametext.setBackground(new Color(Display.getCurrent(), 255, 255,
				255));
		foldernametext.setLocation(new Point(70, 12));
		okbutton = new Button(buttoncomposite, SWT.NONE);
		okbutton.setLocation(new Point(347, 36));
		okbutton.setText("确定");
		okbutton.setSize(new Point(71, 22));
		okbutton
				.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
					public void widgetSelected(
							org.eclipse.swt.events.SelectionEvent e) {
						System.out.println("选择的文件夹绝对路径为：" + folderabsolutepath);
					}
				});
		cancelbutton = new Button(buttoncomposite, SWT.NONE);
		cancelbutton.setText("取消");
		cancelbutton.setSize(new Point(71, 22));
		cancelbutton.setLocation(new Point(259, 36));
		// 单击取消按钮时，关闭该窗口
		cancelbutton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				System.out.println("单击取消时，关闭该窗口");
				closeFolderSelectDialog();
			}
		});
	}

	/**
	 * 读取文件系统中的文件夹目录，并以树状结构显示
	 * 
	 * @param Composite
	 *            parent 树组件显示的区域
	 */
	protected void creatTreeControl(final Composite parent) {
		// folderdirectree = new Tree(parent, SWT.FULL_SELECTION);
		// folderdirectree = new Tree(parent, SWT.BORDER);
		folderdirectree = new Tree(parent, SWT.NONE);
		folderdirectree.setSize(426, 360);// 设置树形控件的大小
		folderdirectree.setHeaderVisible(false);// 表头不可见
		folderdirectree.setLinesVisible(false);// 表格线不可见
		// ---------显示最顶层的节点“我的电脑”---------------
		TreeItem computer = new TreeItem(folderdirectree, SWT.NONE);
		computer.setText("我的电脑");
		//Image computericon = new Image(parent.getDisplay(),"icons//mycomputer.png");// 创建图像
		//computer.setImage(computericon);
		// ---------显示顶层的节点“系统磁盘”---------------
		// 返回可获得的文件根目录，即本地文件系统结构的最顶层（如Windows平台上的盘符）
		File[] disks = File.listRoots();
		//Image systemdiskicon = new Image(parent.getDisplay(), "icons//系统磁盘.png");// 创建磁盘图像
		for (int i = 0; i < disks.length; i++) {
			// TreeItem sysdisk = new TreeItem(tree, 0);
			TreeItem sysdisknode = new TreeItem(computer, 0);
			sysdisknode.setText(disks[i].toString());
			sysdisknode.setData(disks[i]);// 保存当前节点数据
			//sysdisknode.setImage(systemdiskicon);
			new TreeItem(sysdisknode, 0);// 把当前节点作为目录节点
		}
		// ------展开树状结构时，显示相应目录下的系统文件夹（不显示面向用户隐藏的文件夹）节点-----------
		folderdirectree.addListener(SWT.Expand, new Listener() {
			public void handleEvent(final Event event) {
				final TreeItem foldernode = (TreeItem) event.item;
				//Image foldericon = new Image(parent.getDisplay(),"icons//文件夹图标.png");// 创建文件夹图像
				TreeItem[] items = foldernode.getItems();
				for (int i = 0; i < items.length; i++) {
					if (items[i].getData() != null)
						return;
					items[i].dispose();
				}
				File file = (File) foldernode.getData();
				File[] files = file.listFiles();// 返回File对象（文件夹与文件）的数组
				// 采用文件夹目录过滤器来判断当前路径是否为文件夹，返回File对象（文件夹）的数组
				// File[] files = file.listFiles(new DirFilter());
				// 列出该目录中的文件名与文件夹名，返回一个文件名数组
				// String[] filespath=file.list();
				// for (int i = 0; i < filespath.length; i++) {
				// System.out.println("文件为： " + filespath[i]);
				// }
				if (files == null)
					return;
				for (int i = 0; i < files.length; i++) {
					// 不显示隐藏文件的路径

					// if(files[i].isHidden()==false){//判断当前路径的文件是否为隐藏文件
					if ((files[i].isHidden() == false)
							&& (files[i].isFile() == false)) {// 判断当前路径是否为隐藏文件与文件夹
						TreeItem item = new TreeItem(foldernode, 0);
						item.setText(files[i].getName());
						// 叶子节点对应的数值为相应文件夹的File对象
						item.setData(files[i]);
						//item.setImage(foldericon);// 设置文件夹图标
						// 当前为文件目录而不是文件的时候，添加新项目，以便只是显示文件夹（包括空文件夹），而不显示文件夹下的文件
						if (files[i].isDirectory()) {
							new TreeItem(item, 0);
						}
					}
				}
			}
		});
		// -------鼠标单击选择树的叶子节点时，在文本框中显示所选中的文件夹名---------------
		folderdirectree.addListener(SWT.MouseDown, new Listener() {
			public void handleEvent(Event event) {
				Point point = new Point(event.x, event.y);
				TreeItem item = folderdirectree.getItem(point);
				if ((item != null) && (item.getData() != null)) {
					System.out.println("您选中的文件夹名是：" + item);
					System.out.println("您选中的文件夹路径是：" + item.getData());
					foldernametext.setText(item.getText());// 选中文件夹的同时在文本框中显示文件夹名
					// 选择的文件夹路径
					folderabsolutepath = (File) item.getData();

				}
			}
		});
		// ------根据Tree的大小更改树状控件显示区域的大小--------
		// Point size = folderdirectree.computeSize(300, SWT.DEFAULT);
		// int width = Math.max(300, size.x);
		// int height = Math.max(300, size.y);
		// parent.setSize(parent.computeSize(width, height));
	}

	/**
	 * 在文件夹选择对话框中，单击确定按钮
	 */
	protected void selectFolder() {
		// TODO 传递当前选中的文件夹信息，如绝对路径、文件夹名、文件夹的大小等

		// 关闭当前窗口
		closeFolderSelectDialog();
	}

	/**
	 * 计算文件夹目录下文件的整体大小(单位为：字节)
	 */
	public long getDirectorySize(File dir) {
		long retSize = 0;// 文件夹目录下文件的大小
		if ((dir == null) || !dir.isDirectory()) {
			return retSize;
		}
		File[] entries = dir.listFiles();
		int count = entries.length;
		for (int i = 0; i < count; i++) {
			if (entries[i].isDirectory()) {
				retSize += getDirectorySize(entries[i]);
			} else {
				retSize += entries[i].length();
			}
		}
		return retSize;
	}

	/**
	 * 采用内部类实现的文件夹过滤器 文件夹（不显示面向用户隐藏的文件夹）路径过滤器
	 */
	public class DirFilter implements FilenameFilter {

		@Override
		public boolean accept(File dir, String name) {
			File files = new File(dir, name);
			// 返回当前目录下的文件夹路径
			if ((files.isDirectory()) && (files.isHidden() == false)) {
				return true;
			} else {
				return false;
			}
		}
		/**
		 * 实现文件夹过滤器的内部类测试代码
		 */
		/*
		 * public static void main(String[] args) { File dir=new File("C://");
		 * String[] files=dir.list(new DirFilter());
		 * System.out.println(files.length+"dir(s):"); for(String file:files){
		 * System.out.println("/t"+file); } }
		 */
	}

	/**
	 * 文件夹选择对话框测试代码
	 */
	public static void main(String[] args) {
		FolderSelectDialog fd = new FolderSelectDialog();
		fd.openFolderSelectDialog();
	}

}